use std::env;
use std::process::Command;

use actix_files::Files;
use actix_web::{ HttpServer, App };

mod curd;
use curd::init;

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    match env::consts::OS {
        "windows" =>  {
            let _ = Command::new("cmd.exe").arg("/C").arg("start").arg("http://localhost:8080").spawn();
        },
        "linux" => {
            println!("Linux 版本不支持自动打开浏览器, 请手动打开浏览器访问 http://localhost:8080, 服务器外网访问 请把 0.0.0.0 手动替换 IP 或域名。");
        },
        _ => panic!("MAC OS?"),
    };

    let logo = 
    r#"
                       __           _ _       
                      / / _ __ __ _(_|_)_ __  
                     / / | '__/ _` | | | '_ \ 
                    / /__| | | (_| | | | | | |
                    \____/_|  \__,_|_|_|_| |_|

        System: student management system  
        Version: 0.1.0
        Author: @Lraiin -> Lraiin@outlook.com
        Git Repository: https://atomgit.com/shazengchao/stu_manager

        URL: 0.0.0.0:8080
    "#;
    
    println!("{}", logo);
    
    // Data Initialize
    if std::path::Path::new("./data/data.db").exists() {
        println!("Data Initialize is successful! Service is running...");
    } else {
        println!("Data is not exists. Initializing data...");
        match init::initialize_sql() {
            Ok(()) => println!("Data Initialize is successful! Service is running..."),
            Err(e) => panic!("Data Initialize is failed! {}", e),
        }
    }

    HttpServer::new(|| {
        App::new()
            .service(curd::student::read::student_list)
            .service(curd::student::read::rank_list)
            .service(curd::student::read::class_list)

            .service(curd::student::update::update_student)
            .service(curd::student::update::batch_add_students)

            .service(curd::student::delete::delete_student)
            .service(Files::new("/", "./web").index_file("index.html"))
    })
    .bind(("0.0.0.0", 8080))?
    .run()
    .await
}